Kotlin

Creating Your First Android App In Kotlin

kotlin android tutorial
Written by Yasir Ameen

Kotlin is a modern new programming language. Google announced Kotlin as an official programming language for developing Android application in Google IO 2016. Kotlin is developed by JetBrains from the same team which is developed Android Studio and IntelliJ. Kotlin is Java Virtual Machine that means it can be run in any JVM. According to the one survey Kotlin will surpasses Java in 2018 which means there will more developer of Kotlin instead of Java for Android. This will be first part of the series Kotlin android tutorial

Let’s Start Android Development with Kotlin

Configuring Android Studio For Kotlin

If you are using Android Studio 3.0, then you will not need to follow these steps because there is built-In kotlin support in AS 3.0, all you need to just convert your Activity class into Kotlin class, see later down below.

Step 1) Create a project in Android studio and Select Empty Activity.

kotlin for android developers

Step 2) Goto File > Settings > and select plugins from the left menu and click Install JetBrains plugin…

Started with Kotlin on Android

Step 3) Type Kotlin in search bar and click install button, downloading will start, after downloading Android Studio will ask you to restart.

kotlin android tutorial

Step 4) After Android Studio restarts, open your MainActivity.java class and goto Code menu and select “Convert Java File to Kotlin File”.

android kotlin programming

Step 5) After Clicking “Convert Java File to Kotlin File” your MainActivity.java will change to MainActivity.kt, now all you need to rebuild your project from the Build menu, after your program successfully build, Android Studio will ask you to configure kotlin, by clicking configure, the following dialog will appear

Android Development with Kotlin

Step 6 – Last Step) After clicking “OK” you will redirect to gradle file, Android Studio will ask you to Sync Now. Just click the Sync Now and you are now ready to use Kotlin in your project.

android studio sync gradle kotlin

What are basics in Kotlin?

Before going further, lets understand some basics of Kotlin programming with kotlin code example then we will  create an app in Android using Kotlin later in this article.

Vals and vars

Kotlin provide two keywords for declaring variables, val and var . The var is mutable variable which means you can change its value by reassigning it, and val keywords is used to declare a immutable variable or read-only variable which is unable to change or reassign.

kotlin code examples

Arrays

You can create an array in Kotlin using the library function arrayOf()
kotlin code examples

Ranges

In Kotlin, ranges is an interval that has a start and end value. Any compatible type can be used to create a range. You use .. operator to create a range.

kotlin android studio

Loops

Kotlin supports the traditional loops for, while and do-while. The while and do-while is exactly the same as C-language but there is changes in for-loop. The for-loop in Kotlin is used to iterate over any object that support iterator.

kotlin for beginners

Creating a simple app Famous Quotes

Now its time to create a simple app using Kotlin, you have basic idea of Kotlin syntax and we will use these in our simple app “Famous Quotes”. Let’s Start

Step 1) Placing a listview

Open your activity_main.xml  and paste the following xml code, actually we have places a ListView widget which will be used in our app to showing quotes.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.yasir.kotlindemo.MainActivity">

    <ListView
        android:id="@+id/mListView"
        android:divider="@android:color/transparent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
      />
    
</RelativeLayout>

Step 2) Creating a list_item layout

Create a layout xml file in your res folder and call it list_item.xml we will use it for the blue print for the each quote in our app, here is the code

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="15dp"
        android:layout_height="80dp">
        <TextView
            android:id="@+id/quotes"
            android:text="Life is what happens to you while you’re busy making other plans. "
            android:layout_width="match_parent"
            android:lines="2"
            android:textColor="#000"
            android:ellipsize="end"
            android:layout_marginLeft="5dp"
            android:textSize="16sp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/quotesBy"
            android:text="–John Lennon"
            android:layout_marginTop="5dp"
            android:textSize="14sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>

Here is the preview…

android listview kotlin example

Step 3) Creating a Qoutes Information

Create class for our quotes in your project and call it QuotesData , this is just a simple class which will hold our quotes information. You will also see new keyword companion object and its my favorite, read the comments

class QuotesData {

    //Companion Object is something like static field in java,
    //If you want to make something static, put inside in companion object
    companion object {

        val quotes = arrayOf(
                "Life is what happens to you while you’re busy making other plans.",
                "The most common way people give up their power is by thinking they don’t have any.",
                "The best time to plant a tree was 20 years ago. The second best time is now.",
                "I am not a product of my circumstances. I am a product of my decisions.",
                "Every child is an artist.  The problem is how to remain an artist once he grows up",
                "ou can never cross the ocean until you have the courage to lose sight of the shore.",
                "The two most important days in your life are the day you are born and the day you find out why.",
                "Whatever you can do, or dream you can, begin it.  Boldness has genius, power and magic in it.",
                "People often say that motivation doesn’t last. Well, neither does bathing.  That’s why we recommend it daily."
        )
        val quotesBy = arrayOf(
                "–John Lennon",
                "–Alice Walker",
                "–Chinese Proverb",
                "–Stephen Covey",
                "–Pablo Picasso",
                "–Christopher Columbus",
                "–Mark Twain",
                "–Johann Wolfgang von Goethe",
                "–Zig Ziglar"
        )

    }

}

Step 4) Creating a Adapter for Quotes App

Create a class in your project and name it ListAdapter and paste the following code, we are using BaseAdapter for creating our custom listview for our app. (Don’t forget to read the comments)

Important : Read the code care fully and understand how easy Kotlin Programming is.

//We define a constructor in Kotlin within declaring a class
class ListAdapter(context: Context) : BaseAdapter() {


    private var inflater: LayoutInflater? = null

    //The constructor parameters are initialize in init block
    //which means whenever we will initiaze a class, init block will execute
    init {
        inflater = LayoutInflater.from(context)
    }

    override fun getView(position: Int, convertview: View?, parent: ViewGroup?): View {

        var convertview = convertview
        val holder: ViewHolder
        if (convertview == null) {

            convertview = inflater!!.inflate(R.layout.list_item, null)
            holder = ViewHolder()
            holder._tv_quotes = convertview.findViewById(R.id.quotes)
            holder._tv_quotesBy = convertview.findViewById(R.id.quotesBy)

            convertview.tag = holder

        } else {
            holder = convertview.tag as ViewHolder
        }

        holder._tv_quotes?.text = QuotesData.quotes[position]
        holder._tv_quotesBy?.text = QuotesData.quotesBy[position]

        return convertview!!

    }

    //In Kotlin whenever function return a single statment or expression, we can create a single line function
    override fun getItem(position: Int): Any = QuotesData.quotes.size

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getCount(): Int = QuotesData.quotes.size

    inner class ViewHolder {

         var _tv_quotes: TextView? = null
         var _tv_quotesBy: TextView? = null

    }
}

Final Step) Putting Everything together

Now open your MainActivity.kt and paste the following code.

class MainActivity : AppCompatActivity() {

    private var listview: ListView? = null

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

        //Creating instance of ListAdapter Class
        val listAdapter = ListAdapter(this)

        listview = findViewById(R.id.mListView)
        listview?.adapter = listAdapter


        //Creating List Item Click Listener..
        listview?.setOnItemClickListener { parent, view, position, id ->

            Toast.makeText(this@MainActivity,QuotesData.quotesBy[position],Toast.LENGTH_LONG).show()
        }
    }
}

Run the and app enjoy your very first app in Kotlin 🙂

Here is the final preview of our Famous Quotes app.

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

1 Comment

Leave a Comment