Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Kotlin For Android: An Introduction

$
0
0

Update Note: This tutorial has been updated to Android Studio 3.0 by Joe Howard. The original tutorial was written by Eunice Obugyei.

Kotlin-feature

Until recently, app development on Android was almost exclusively done using the Java programming language, and Java 6 at that. Java 6 was introduced in 2006, two years before the release of Android devices.

JetBrains, known for IntelliJ IDEA (Android Studio is based on IntelliJ IDEA), introduced the Kotlin language in 2011. Kotlin reached 1.0 status early in 2016.

At Google I/O 2017 in April, Google announced that Kotlin would forever more be supported as a first class programming language Android. And the soon to be released Android Studio 3.0 will support Kotlin out of the box! :]

While Java 8 is now supported on recent Android releases and will continue to be supported on Android by Google, recent developer surveys indicate that Kotlin will soon dominate as an Android app development language.

Kotlin is a statically-typed programming language that runs on the JVM. It can also be compiled to JavaScript source code and to native executables. Kotlin has some amazingly cool features!

In this Kotlin for Android tutorial, you’ll learn:

  • Setup your Kotlin environment.
  • How to work with both Java and Kotlin in the same project.
  • What makes Kotlin so exciting as a new language.
Note: This tutorial assumes you’re experienced in Android development with Java. If you’re new to the Android world, have big questions about the starter project or are not familiar with Android Studio, please have a look at our Android tutorials. Also, this tutorial assumes that you’re using Android Studio 3.0 RC2 or later.

Why Kotlin For Android?

Since Android took the world by storm, developers have had few alternatives to Java for app development. Although its usage is widespread, Java comes with a lot of historical baggage.

Java 8 solved some language issues and even more were corrected with Java 9 and 10. But you have to set the minimum SDK to Android 24 just to use Java 8, which isn’t an option for many developers. For almost everybody, Java 9 and 10 aren’t even on the radar. :]

Kotlin aims to fill that gap of a missing modern language for the Android platform. There are a few core tenets that Kotlin lives by; it strives to be:

  1. Concise to reduce the amount of boilerplate code you need to write.
  2. Expressive to make your code more readable and understandable.
  3. Safe to avoid entire classes of errors such as null pointer exceptions.
  4. Versatile for building server-side applications, Android apps or frontend code running in the browser.
  5. Interoperable to leverage existing frameworks and libraries of the JVM with 100 percent Java interoperability.

Above all, it’s a new language! What could be more exciting? iOS developers can’t have all the fun. :]

Getting Started

Download the starter project. Extract and open the starter project in Android Studio 3.0 or later.

You’ll be working with this simple app that allows users to search for books, see book covers, and share books with friends to explore Kotlin.

It contains three source code files; take a moment to get familiar with them:

  • MainActivity.java: an Activity that displays the screen for searching and displaying a list of books.
  • DetailActivity.java: an Activity that displays the book cover for the ID passed to it.
  • JSONAdapter.java: a custom BaseAdapter that transforms a JSON object into a list view item.

Build and run the project to see what you’re working with.

Setting up Your Environment

Android Studio 3.0 and later support Kotlin right out of the box. Any new projects you create will be configured to use Kotlin, as long as you’ve checked the “Include Kotlin support” checkbox when creating the project (you won’t need to create a project for this tutorial since it’s provided as a starter project above):

You’ll occasionally be prompted to update your Kotlin plugin in Android Studio 3.0, when the application first opens. You can always check your Kotlin plugin version on the Plugins screen by hitting command+shift+a and typing “Plugins”, then typing Kotlin into the search box:

Working with Java and Kotlin in the Same Project

One of the most amazing qualities of Kotlin is how it can coexist with Java on a project. Java code can be called from Kotlin and vice versa.

From this point of the tutorial forward, you’ll be translating the DetailActivity class into Kotlin.

Single click the com.raywenderlich.android.omgandroid package in the Project panel on the left-hand side. With the package selected, go to File\New\Kotlin File/Class to create a new Kotlin class. (Without the package selected, you won’t see the Kotlin file option).

On the New Kotlin File/Class popup, select Class in the Kind field and enter DetailActivityKotlin as the class name. Click OK.

intro_to_kotlin_17

Your new class should look like this:

package com.raywenderlich.android.omgandroid

class DetailActivityKotlin {
}

A few things to note here:

  1. As you may have noticed in the above code, classes in Kotlin are declared using the keyword class — just like in Java.
  2. By default, if no visibility modifier is present in Kotlin, then the item is public.
  3. Classes and methods are final by default. You can declare them open if you want extensibility.

Since Kotlin is Java interoperable, you can use existing Java frameworks and libraries in your Kotlin code files.

Make the class a subclass of AppCompatActivity.

class DetailActivityKotlin : AppCompatActivity() {

}

If needed, hit Option+Return to import necessary classes such as AppCompatActivity. Android Studio will usually add the import statements for you if there are no conflicts.

Note that you do this in Kotlin a little differently from how you do it in Java. In Kotlin, you append : NameOfParentClass() to the subclass declaration. The trailing parentheses are for the constructor on the parent class.

Now override Activity‘s onCreate() method. It will look something like this.

import android.app.Activity
import android.os.Bundle

class DetailActivityKotlin: Activity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
  }
}
Note: You can use Android Studio’s code generation functionality to generate the onCreate method signature with control + O. Press control + O to see a popup with all overridable methods for the class you’re in.

intro_to_kotlin_18

Open MainActivity.java and replace the DetailActivity reference in onItemClick() with DetailActivityKotlin.

Your intent creation line should change from:

Intent detailIntent = new Intent(this, DetailActivity.class);

To this:

Intent detailIntent = new Intent(this, DetailActivityKotlin.class);

Just like you would do for a Java Activity, you need to declare your Kotlin Activity in AndroidManifest.xml. Add the following code under the DetailActivity declaration:

<activity
    android:name=".DetailActivityKotlin"
    android:label="@string/activity_details_kotlin"
    android:parentActivityName=".MainActivity">
  <meta-data
      android:name="android.support.PARENT_ACTIVITY"
      android:value=".MainActivity"/>
</activity>

Build and run. Select a book from the list so you can see that empty screen with the title Kotlin Book Details.

How Cool is Kotlin?

Before you dive deeper into Kotlin’s features, go back to DetailActivityKotlin.kt and replace the contents of the file with the following:

package com.raywenderlich.android.omgandroid

import android.content.Intent
import android.os.Bundle
import android.support.v4.view.MenuItemCompat
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.widget.ImageView
import android.support.v7.widget.ShareActionProvider
import com.squareup.picasso.Picasso

class DetailActivityKotlin : AppCompatActivity() {

  private val imageUrlBase = "http://covers.openlibrary.org/b/id/"
  private var imageURL = ""
  private var shareActionProvider: ShareActionProvider? = null

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_detail)

    actionBar?.setDisplayHomeAsUpEnabled(true)

    val imageView = findViewById<ImageView>(R.id.img_cover)

    val coverId = this.intent.extras.getString("coverID")

    val len = coverId?.length ?: 0

    if (len > 0) {
      imageURL = imageUrlBase + coverId + "-L.jpg"
      Picasso.with(this).load(imageURL).placeholder(R.drawable.img_books_loading).into(imageView)
    }
  }

  private fun setShareIntent() {

    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.type = "text/plain"
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Book Recommendation!")
    shareIntent.putExtra(Intent.EXTRA_TEXT, imageURL)

    shareActionProvider?.setShareIntent(shareIntent)
  }

  override fun onCreateOptionsMenu(menu: Menu): Boolean {

    menuInflater.inflate(R.menu.main, menu)

    val shareItem = menu.findItem(R.id.menu_item_share)

    shareActionProvider = MenuItemCompat.getActionProvider(shareItem) as ShareActionProvider

    setShareIntent()

    return true
  }
}

On the surface, the code resembles Java, but there are some Kotlin language specifics that you’ll get into in the next section.

Build and run, select a book and see if you get a cover this time. Oh, look, you do!

Null Safety

One of the leading points of frustration with most programming languages, including Java, is accessing a member of a null reference. A null reference occurs when you declare an object variable but haven’t given it a value. When the program runs and tries to access that variable it doesn’t know where to look for it memory because it doesn’t exist.

The most common result of this is your application coming to an abrupt halt and crashing! You might be familiar with Java’s “almighty” NullPointerException. Apologies in advance for any flashbacks! :]

null_pointer_exception

One of Kotlin’s greatest features is that its type system aims to eliminate the NullPointerException (a goal known as void safety).

In Kotlin, the only possible causes of a NullPointerException are:

  • External Java code did it
  • An explicit call to throw NullPointerException()
  • Usage of the !! operator (which will be explained shortly)
  • Some data inconsistency in regards to initialization

Nullable Types and Non-Null Types

Kotlin has nullable and non-null types. If you don’t declare a variable as nullable, then you cannot assign it a null value. This is enforced by the compiler, so it’s much harder to unintentionally crash your app.

In contrast to Java, all variables must be initialized at the point of declaration.

To declare a variable as nullable, you have to append a ? to its type at the point of declaration, as you see in this shareActionProvider declaration:

private var shareActionProvider: ShareActionProvider? = null

Safe Calls

To access a property or method on a nullable variable in Java, you would first do a null check. You can see this in DetailActivity.java:

if (shareActionProvider != null) {
  shareActionProvider.setShareIntent(shareIntent);
}

With Kotlin, you can simplify the above expression with the use of a safe call operator (?.). The property or method is only called when the nullable variable is not null.

shareActionProvider?.setShareIntent(shareIntent)

Here, setShareIntent is only called when the shareActionProvider property is not null.

The !! Operator

As stated earlier, this is one of possible causes of the dreaded NullPointerException. If you’re absolutely sure a nullable object is not null, feel free to use the !! operator to dereference your object.

You can see an example of this in setShareIntent():

shareActionProvider = MenuItemCompat.getActionProvider(shareItem!!) as ShareActionProvider

In here, a NullPointerException is thrown if the shareItem variable is null.

The Elvis Operator

The Elvis Operator (?:) looks like the ternary conditional operator in Java, but works differently. You can see an example of this when trying to get the length of the cover ID:

val len = coverId?.length ?: 0

If the expression to the left of the Elvis operator is not null, the results of the expression are returned. Otherwise, the it returns the expression to the right.

Similarly to an if-else statement, Elvis only evaluates the expression on the right if the one on the left side is null.

Type Inference

Kotlin also supports type inference, meaning the compiler can assume its type from the initializer when a variable is declared and initialized. For example, the types of the imageUrlBase and imageURL variables are inferred from their initializers.

private val imageUrlBase = "http://covers.openlibrary.org/b/id/"
private var imageURL = ""

The compiler tracks the inferred type of each variable (each is a String), and any subsequent values assigned to the variable must also be of that type (String).

The Coolest of Them All

Already thinking of rewriting your Java project in Kotlin? Don’t stress — the Android Studio Kotlin plugin has you covered.

Since Kotlin is a programming language made by developers for developers, it’s designed to make your life as easy as possible. The Kotlin plugin even has a handy tool that allows you to convert a Java source file to Kotlin.

Take this sanity-saving feature for a test drive by converting the DetailActivity.java file to Kolin.

Open the DetailActivity.java class and go to Code\Convert Java File to Kotlin File.

Click OK on the Convert Java to Kotlin screen. This will replace the Java file with a Kotlin one!

intro_to_kotlin_14

That’s it. You’ve converted a Java class into a Kotlin class. :]

Compare the converted DetailActivity with the DetailActivityKotlin class you made manually to see some of the choices the converter made.

You can reset MainActivity to refer to the newly converted code:

Intent detailIntent = new Intent(this, DetailActivity.class);

Build and run and go to the detail screen, and you’ll see the converted code works just as well as the code you typed in. :]

Where To Go From Here?

Congratulations! You just learned about the Kotlin programming language and some of it’s amazing features, re-coded a Java Activity in Kotlin, and used the Kotlin plugin to convert a Java source file into a Kotlin source file.

Download the final project for this tutorial here.

I suggest reading up further on Null Safety in Kotlin in the documentation.

You can also use the Kotlin online compiler to try out code samples and improve your knowledge of the language.

You’ve only scratched the surface of the amazing possibilities with Kotlin. If you’re excited by what you’ve read here, you can checkout topics such as Data Classes, Extensions, Lambdas, or String Templates if you need to satisfy your appetite for knowledge.

I hope you enjoyed this Kotlin for Android tutorial, and if you have any questions or comments, please join the forum discussion below!

The post Kotlin For Android: An Introduction appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>