Showing posts with label Kotlin. Show all posts

In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin . It is similar to the way of implementing SQL...

Android SQLite Tutorial - Kotlin Android SQLite Tutorial - Kotlin

A blog about android developement

Kotlin

In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin. It is similar to the way of implementing SQLite using Java. To learn the basics of Kotlin click here.

Project Setup:

Create new Project with Kotlin Support in Android Studio 3.0 or If you are using Android Studio version below 3.0 then setup Kotlin Plugin.

Coding Part

Create a kotlin class named as Tasks.kt and paste the following code
class Tasks {

    var id: Int = 0
    var name: String = ""
    var desc: String = ""
    var completed: String = "N"

}
DatabaseHandler
Create a Kotlin class named as DatabaseHandler.kt. It is used to Handle the database operations of SQLite with Kotlin. The Parent of this class is SQLiteOpenHelper. Paste the following code in DatabaseHandler.kt
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) {

    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);"
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME"
        db.execSQL(DROP_TABLE)
        onCreate(db)
    }
}

CRUD Operations of SQLite

Now we need to write methods for handling all database read and write operations. Here we are implementing following methods for our tasks table.

Insert data to Table
The following code is used to add tasks to SQLite.
fun addTask(tasks: Tasks): Boolean {
 val db = this.writableDatabase
 val values = ContentValues()
 values.put(NAME, tasks.name)
 values.put(DESC, tasks.desc)
 values.put(COMPLETED, tasks.completed)
 val _success = db.insert(TABLE_NAME, null, values)
 db.close()
 Log.v("InsertedId", "$_success")
 return (Integer.parseInt("$_success") != -1)
}
Get all data from Table
The following code is used to get all tasks from SQLite.
fun task(): List {
 val taskList = ArrayList()
 val db = writableDatabase
 val selectQuery = "SELECT  * FROM $TABLE_NAME"
 val cursor = db.rawQuery(selectQuery, null)
 if (cursor != null) {
  if (cursor.moveToFirst()) {
   do {
    val tasks = Tasks()
    tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
    tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
    tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
    tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
    taskList.add(tasks)
   } while (cursor.moveToNext())
  }
 }
 cursor.close()
 return taskList
}
Get particular data from Table
The following code is used to get particular task from SQLite.
fun getTask(_id: Int): Tasks {
 val tasks = Tasks()
 val db = writableDatabase
 val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $ID = $_id"
 val cursor = db.rawQuery(selectQuery, null)

 cursor?.moveToFirst()
 tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
 tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
 tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
 tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
 cursor.close()
 return tasks
}
Update data to Table
The following code is used to update particular task to SQLite.
fun updateTask(tasks: Tasks): Boolean {
 val db = this.writableDatabase
 val values = ContentValues()
 values.put(NAME, tasks.name)
 values.put(DESC, tasks.desc)
 values.put(COMPLETED, tasks.completed)
 val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toString())).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}
Delete data from Table
The following code is used to delete particular or all task(s) from SQLite.
// delete particular data
fun deleteTask(_id: Int): Boolean {
 val db = this.writableDatabase
 val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}

// delete all data
fun deleteAllTasks(): Boolean {
 val db = this.writableDatabase
 val _success = db.delete(TABLE_NAME, null, null).toLong()
 db.close()
 return Integer.parseInt("$_success") != -1
}
Full Code of DatabaseHandler
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) {

    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);"
        db.execSQL(CREATE_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME"
        db.execSQL(DROP_TABLE)
        onCreate(db)
    }

    fun addTask(tasks: Tasks): Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(NAME, tasks.name)
        values.put(DESC, tasks.desc)
        values.put(COMPLETED, tasks.completed)
        val _success = db.insert(TABLE_NAME, null, values)
        db.close()
        Log.v("InsertedId", "$_success")
        return (Integer.parseInt("$_success") != -1)
    }

    fun getTask(_id: Int): Tasks {
        val tasks = Tasks()
        val db = writableDatabase
        val selectQuery = "SELECT  * FROM $TABLE_NAME WHERE $ID = $_id"
        val cursor = db.rawQuery(selectQuery, null)

        cursor?.moveToFirst()
        tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
        tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
        tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
        tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
        cursor.close()
        return tasks
    }

    fun task(): List {
        val taskList = ArrayList()
        val db = writableDatabase
        val selectQuery = "SELECT  * FROM $TABLE_NAME"
        val cursor = db.rawQuery(selectQuery, null)
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    val tasks = Tasks()
                    tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID)))
                    tasks.name = cursor.getString(cursor.getColumnIndex(NAME))
                    tasks.desc = cursor.getString(cursor.getColumnIndex(DESC))
                    tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED))
                    taskList.add(tasks)
                } while (cursor.moveToNext())
            }
        }
        cursor.close()
        return taskList
    }

    fun updateTask(tasks: Tasks): Boolean {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(NAME, tasks.name)
        values.put(DESC, tasks.desc)
        values.put(COMPLETED, tasks.completed)
        val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toString())).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    fun deleteTask(_id: Int): Boolean {
        val db = this.writableDatabase
        val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    fun deleteAllTasks(): Boolean {
        val db = this.writableDatabase
        val _success = db.delete(TABLE_NAME, null, null).toLong()
        db.close()
        return Integer.parseInt("$_success") != -1
    }

    companion object {
        private val DB_VERSION = 1
        private val DB_NAME = "MyTasks"
        private val TABLE_NAME = "Tasks"
        private val ID = "Id"
        private val NAME = "Name"
        private val DESC = "Desc"
        private val COMPLETED = "Completed"
    }
}

Add Tasks

The following code is used to call Insert Function in DatabaseHandler
val tasks: Tasks = Tasks()
tasks.name = input_name.text.toString()
tasks.desc = input_desc.text.toString()
if (swt_completed.isChecked)
 tasks.completed = "Y"
else
 tasks.completed = "N"
success = dbHandler?.addTask(tasks) as Boolean

Update Tasks

The following code is used to call update Function in DatabaseHandler
val tasks: Tasks = Tasks()
tasks.id = intent.getIntExtra("Id", 0)
tasks.name = input_name.text.toString()
tasks.desc = input_desc.text.toString()
if (swt_completed.isChecked)
 tasks.completed = "Y"
else
 tasks.completed = "N"
success = dbHandler?.updateTask(tasks) as Boolean

Delete Tasks

The following code is used to call delete Functions in DatabaseHandler
// Delete Task
val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean
// Delete All Tasks
dbHandler!!.deleteAllTasks()

Read Tasks

The following code is used to call read Functions in DatabaseHandler
// Read All Tasks
val tasks: Tasks = dbHandler!!.getTask(intent.getIntExtra("Id",0))
// Read Particular Task
dbHandler = DatabaseHandler(this)
listTasks = (dbHandler as DatabaseHandler).task()
In this tutorial, I have used Recyclerview. To implement Recyclerview click here.

Full Code of this tutorial

Create MainActivity.kt and Paste the following code
class MainActivity : AppCompatActivity() {

    var taskRecyclerAdapter: TaskRecyclerAdapter? = null;
    var fab: FloatingActionButton? = null
    var recyclerView: RecyclerView? = null
    var dbHandler: DatabaseHandler? = null
    var listTasks: List = ArrayList()
    var linearLayoutManager: LinearLayoutManager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        initOperations()
        //initDB()
    }

    fun initDB() {
        dbHandler = DatabaseHandler(this)
        listTasks = (dbHandler as DatabaseHandler).task()
        taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext)
        (recyclerView as RecyclerView).adapter = taskRecyclerAdapter
    }

    fun initViews() {
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
        fab = findViewById(R.id.fab) as FloatingActionButton
        recyclerView = findViewById(R.id.recycler_view) as RecyclerView
        taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext)
        linearLayoutManager = LinearLayoutManager(applicationContext)
        (recyclerView as RecyclerView).layoutManager = linearLayoutManager
    }

    fun initOperations() {
        fab?.setOnClickListener { view ->
            val i = Intent(applicationContext, AddOrEditActivity::class.java)
            i.putExtra("Mode", "A")
            startActivity(i)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == R.id.action_delete) {
            val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete All Tasks")
                    .setPositiveButton("YES", { dialog, i ->
                        dbHandler!!.deleteAllTasks()
                        initDB()
                        dialog.dismiss()
                    })
                    .setNegativeButton("NO", { dialog, i ->
                        dialog.dismiss()
                    })
            dialog.show()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onResume() {
        super.onResume()
        initDB()
    }
}
Create AddOrEditActivity.kt and Paste the following code
class AddOrEditActivity : AppCompatActivity() {

    var dbHandler: DatabaseHandler? = null
    var isEditMode = false

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_edit)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        initDB()
        initOperations()
    }

    private fun initDB() {
        dbHandler = DatabaseHandler(this)
        btn_delete.visibility = View.INVISIBLE
        if (intent != null && intent.getStringExtra("Mode") == "E") {
            isEditMode = true
            val tasks: Tasks = dbHandler!!.getTask(intent.getIntExtra("Id",0))
            input_name.setText(tasks.name)
            input_desc.setText(tasks.desc)
            swt_completed.isChecked = tasks.completed == "Y"
            btn_delete.visibility = View.VISIBLE
        }
    }

    private fun initOperations() {
        btn_save.setOnClickListener({
            var success: Boolean = false
            if (!isEditMode) {
                val tasks: Tasks = Tasks()
                tasks.name = input_name.text.toString()
                tasks.desc = input_desc.text.toString()
                if (swt_completed.isChecked)
                    tasks.completed = "Y"
                else
                    tasks.completed = "N"
                success = dbHandler?.addTask(tasks) as Boolean
            } else {
                val tasks: Tasks = Tasks()
                tasks.id = intent.getIntExtra("Id", 0)
                tasks.name = input_name.text.toString()
                tasks.desc = input_desc.text.toString()
                if (swt_completed.isChecked)
                    tasks.completed = "Y"
                else
                    tasks.completed = "N"
                success = dbHandler?.updateTask(tasks) as Boolean
            }

            if (success)
                finish()
        })

        btn_delete.setOnClickListener({
            val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete the Task.")
                    .setPositiveButton("YES", { dialog, i ->
                        val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean
                        if (success)
                            finish()
                        dialog.dismiss()
                    })
                    .setNegativeButton("NO", { dialog, i ->
                        dialog.dismiss()
                    })
            dialog.show()
        })
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        if (id == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}

Download Code:

You can the download code for this post from Github. If you like this, tutorial star it on Github.

In this tutorial, we will learn how to build ListView and RecyclerView with Custom Adapter in Kotlin. Everybody knows what is Listvi...

RecyclerView & ListView in Kotlin RecyclerView & ListView in Kotlin

A blog about android developement

Kotlin



In this tutorial, we will learn how to build ListView and RecyclerView with Custom Adapter in Kotlin. Everybody knows what is Listview and Recyclerview. So, without any introduction about them we will jump into the coding part of the Tutorial.

Coding Part

Kotlin ListView Example

We should follow the same steps to create Activity with associated layout file for example MainActivity.kt with activity_main.xml

Create ListView Adapter

Create new class and named as MoviesListViewAdapter and paste the following.
class MoviesListViewAdapter(private val activity: Activity, moviesList: List) : BaseAdapter() {

    private var moviesList = ArrayList()

    init {
        this.moviesList = moviesList as ArrayList
    }

    override fun getCount(): Int {
        return moviesList.size
    }

    override fun getItem(i: Int): Any {
        return i
    }

    override fun getItemId(i: Int): Long {
        return i.toLong()
    }

    @SuppressLint("InflateParams", "ViewHolder")
    override fun getView(i: Int, convertView: View?, viewGroup: ViewGroup): View {
        var vi: View = convertView as View
        val inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        vi = inflater.inflate(R.layout.movie_list_row, null)
        val title = vi.findViewById(R.id.title)
        val genre = vi.findViewById(R.id.genre)
        val year = vi.findViewById(R.id.year)
        title.text = moviesList[i].title
        genre.text = moviesList[i].genre
        year.text = moviesList[i].year
        return vi
    }
}
Then Assign the adapter to ListView like below
listView = findViewById(R.id.listView) as ListView
adapter = MoviesListViewAdapter(this, movieList)
(listView as ListView).adapter = adapter

Kotlin RecyclerView Example

Create RecyclerView Adapter

Create new class and named as MoviesRecyclerAdapter and paste the following.
class MoviesRecyclerAdapter(private val moviesList: List) : RecyclerView.Adapter() {

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var title: TextView = view.findViewById(R.id.title)
        var year: TextView = view.findViewById(R.id.year)
        var genre: TextView = view.findViewById(R.id.genre)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.movie_list_row, parent, false)

        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val Movies = moviesList[position]
        holder.title.text = Movies.title
        holder.genre.text = Movies.genre
        holder.year.text = Movies.year
    }

    override fun getItemCount(): Int {
        return moviesList.size
    }
}
Then Assign the adapter to RecyclerView like below
recyclerView = findViewById(R.id.recyclerView) as RecyclerView
mAdapter = MoviesRecyclerAdapter(movieList)
val mLayoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = mLayoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
recyclerView!!.adapter = mAdapter
In this tutorial, I am not covered the basics of creating listview and recyclerview. You can find the full example in download section

Download Code

You can download the full source code for this tutorial from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Kotlin Android Extensions is an important Kotlin plugin that is similar to Butterknife. It will allow to recover views in android. I...

Kotlin Android Extensions Kotlin Android Extensions

A blog about android developement

Kotlin


Kotlin Android Extensions is an important Kotlin plugin that is similar to Butterknife. It will allow to recover views in android.

Implementation

Add the following plugins in your app level build.gradle file
apply plugin:'com.android.application'
apply plugin:'kotlin-android'
apply plugin:'kotlin-android-extensions'

Coding Part

Create a new layout file in res folder, name it as activity_main.xml and paste the following codes
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.androidmads.kotlinsample_helloworld.MainActivity">

    <TextView
        android:id="@+id/helloTxtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <TextView
        android:id="@+id/helloAndroidExtension"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Hello World!" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        app:srcCompat="@mipmap/ic_launcher" />

</LinearLayout>
Create a new Kotlin file and name it as MainActivity.kt Import the following line, which is used to recover the views in android.
import kotlinx.android.synthetic.main.activity_main.*;
The following code refers that how to use Kotlin Extension. Here helloAndroidExtension is the Id of the textview and click listener for this textview is done as in below code
// Hello Program for Kotlin Android Extension 
// helloAndroidExtension is the id of the TextView
helloAndroidExtension.text = "Example for Kotlin Android Extension";
We can apply the same Approach with imageview by assigning ImageSource from Drawable folder and see the code below.
imageView.setImageResource(R.mipmap.ic_launcher_round)

Full Code

The following shows, how to use Kotlin Android extensions
package com.androidmads.kotlinsample_helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*;

class MainActivity : AppCompatActivity() {

    // Declaration
    var helloTextView: TextView? = null

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

        // Initialization
        helloTextView = findViewById(R.id.helloTxtView) as TextView
        // Assigning data to TextView in runtime
        helloTextView!!.text = "Hello Kotlin!";

        // Click Listener in Kotlin
        helloTextView!!.setOnClickListener({
            Toast.makeText(applicationContext, "Hello TextView Clicked",
                    Toast.LENGTH_LONG).show();
        })

        // Hello Program for Kotlin Android Extension
        helloAndroidExtension.text = "Example for Kotlin Android Extension";

        imageView.setImageResource(R.mipmap.ic_launcher_round)
    }
}

Download Code:

You can download the full source for this tutorial from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Hello Guys, we already knew that Google announced Kotlin is a new first class language for Android Development. So, we started t...

Kotlin - Basics Kotlin - Basics

A blog about android developement

Kotlin


Hello Guys, we already knew that Google announced Kotlin is a new first class language for Android Development. So, we started the Kotlin series for learning Kotlin for android. We have seen the "Hello World" Program for Android in our previous post. 

You can download Intellij idea Commuinty Edition or use Kotlin Online Compiler provided by Intellij

In this post, we will learn the basics of kotlin.

1. Hello World

The Following Snippet shows the Hello world Program and is similar to Java.
fun main(args: Array <string>) {
    println("Hello, world!")
}

2. Variables and Constants

The Following Snippet shows the How to use Variables and Constants with Datatype in Kotlin.
  1. Variables can be re-assigned 
  2. // Variable - Values Can be reassigned
    var a = 10
    a = a + 10
    println(a)
  3. Constants cannot be re-assigned and if we did will error as "val cannot be reassigned"
  4. // Constants - Values cannot reassigned
    val x = 10
    println(x)
  5. We can specify the Data types for Variables and Constants
  6. // Concate String Values
    println(str+"Mad")
    println("${str}Mad - Kotlin Series")
The following snippet shows how to use variables and constants.
fun main(args: Array<string>) {
    // Variable - Values Can be reassigned
    var a = 10
    a = a + 10
    println(a)
    // Constants - Values cannot reassigned
    val x = 10
    println(x)
    // Variables - with Datatype
    var str : String = "Android"
    println(str)
    // Concate String Values
    println(str+"Mad")
    println("${str}Mad - Kotlin Series")
}

3. If Else

The Following Snippet shows the If Else Statement in Kotlin.
fun main(args: Array<string>) {
    var arun = 10
    var dharun = 15
    var elder = if(arun > dharun)"Arun" else "Dharun"
 
    println("Elder is ${elder}")
}

4. When

Switch statement is not present in Kotlin and is replaced by When.
fun main(args: Array<string>) {
    var elder = "Dharun"
    when(elder){
        "Arun"->{
            println("Elder is Arun")
        }
        "Dharun"->{
            println("Elder is Dharun")
        }
        else->{
            println("No Answer")
        }
    }
}

5. Loops

The Following snippet shows Loops in Kotlin.
// For Loop
fun main(args: Array<string>) {
    for(i in 1..10){
        println(i)
    }
}
// While Loop
fun main(args: Array<string>) {
    var x = 1;
    while(x<=10){
        println(x)
        x++
    }
}

6. Arrays and Lists

The Following snippet shows Arrays in Kotlin.
fun main(args: Array<String>) {
    var x = arrayOf(1,2,3,4);
    for(i in x){
        println(i)
    }
}
We can apply any type in like float, string ...
fun main(args: Array) {
    var x = arrayOf(1,2,3,4,"Androidmads");
    for(i in x){
        println(i)
    }
}
It Can be controlled by apply Data types as in the following Snippet
fun main(args: Array<String>) {
    var x = arrayOf<String>("Android","Mads","Kotlin","Series");
    for(i in x){
        println(i)
    }
}
Lists are similar to arrays
fun main(args: Array<String>) {
    var x = listOf<String>("Android","Mads","Kotlin","Series");
    for(i in x){
        println(i)
    }
}

7. Classes

The Following snippet shows how to declare / create objects for class in Kotlin. Create a class named it as "Model.kt"
class Model {
    var name : String = ""
}
fun main(args: Array<String>) {
    // In Java Object Created by ClassObject obj = new ClassObject();
    var model = Model()
    model.name = "Androidmads" 
}

8. Constructors

The Following snippet shows how to use constructor in Kotlin.
class Model(val name:String, val age:Int)
We can also the following method
class Model{
   constructor(name:String, age:Int) {

   }
}
fun main(args: Array<String>) {
    // In Java Object Created by ClassObject obj = new ClassObject();
    var model = Model("Androidmads",20)
    println("${model.name}")
}

9. Null Handling

In Java, Null value may leads to Null Pointer Exception. But, In Kotlin,Null Handling to variables is done as in the following snippet
fun main(args: Array<String>) {
    var name:String? = null
    // Just prints Null and does not throw NullPointerException  
    println("${name}")
}
Hope you Like this. Post Comments about this article in Comment Section 

Google officially announced Kotlin as a first class language for Android development at Google I/O 2017. From Android Studio 3.0, Kotl...

Hello World - Kotlin Hello World - Kotlin

A blog about android developement

Kotlin

Google officially announced Kotlin as a first class language for Android development at Google I/O 2017. From Android Studio 3.0, Kotlin is included as Support for Android Studio. In this post, we will start the development of Android Application with Kotlin.

To Getting Started, you have to download Android Studio 3.0 Canary 1 or Add the Kotlin plugin in your existing Android Studio.

Create Android Project with Kotlin

Create new project in Android studio check the Kotlin support and start as usual with Android Studio 3.0. 
Android Studio 3.0
But for Android Studio with version less than 3.0, we have install plugin form Plugins menu manually by Selecting File-->Settings-->Plugins-->Browse Repositories--> Search and Select Kotlin. Then Click Install

Now inside activity_main.xml create the following UI
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidmads.kotlinsample_helloworld.MainActivity">

    <TextView
        android:id="@+id/helloTxtView"
        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>
In Android Studio 3.0, by default you have Kotin Activity. For Android Studio with Version less than 3.0, can convert their Java activity into Kotlin Activity.
Install Kotlin Plugin
  1. Select Tools --> Kotlin --> Configure Kotlin --> Click Sync Now. 
  2. Open Quick Search or Click Ctrl + Shift + A for Windows Users. 
  3. Search and Select convert java to kotlin or simply Selct Ctrl + Shift + Alt + K for Windows Users. 
Now your MainActivity.kt looks like in the following.
package com.androidmads.kotlinsample_helloworld

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    // Declaration
    var helloTextView: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialization
        helloTextView = findViewById(R.id.helloTxtView) as TextView
        // Assigning data to TextView in runtime
        helloTextView!!.text = "Hello Kotlin!";

        // Click Listener in Kotlin
        helloTextView!!.setOnClickListener({
            Toast.makeText(applicationContext, "Hello TextView Clicked", Toast.LENGTH_LONG).show();
        })
    }
}
Kotlin is a new Programming Language for Android Development. I hope Java is not deprecated for Android Development. Please tell what do you think about this tutorial as well as the future of Java in Android development in Comment Section.