kotlin android app development course, kotlin, null safety

Null Safety in Kotlin

Kotlin is a programming language widely used for Android app development today, designed to complement the shortcomings of Java and allow for safer code writing. Among its features, null safety is one of Kotlin’s greatest advantages, helping developers write code without worrying about null pointer exceptions (NullPointerException).

What is a Null Pointer Exception?

A null pointer exception occurs when a program tries to access a `null` object. In Java, there are many variables that can hold a `null` value, leading to frequent occurrences in programs, which can cause fatal errors. For example:


    String str = null;
    int length = str.length(); // NullPointerException occurs at this line
    

Null Safety in Kotlin

In Kotlin, you can explicitly define whether a variable can hold a null value. By default, all variables are set to be non-null, and to allow null, a special syntax must be used.

Declaring Variables that Allow Null

To allow null, you add the ? symbol to the variable type. For example:


    var name: String? = null  // String variable that allows null
    

Safe Calls (?.) and Elvis Operator (?:)

Kotlin uses the ?. operator for safe calls, allowing you to check if an object is null before calling methods. If the object is null, the method is not called, and null is returned.

For example:


    var name: String? = null
    println(name?.length)  // Output: null
    

Additionally, you can use the Elvis operator (?:) to provide a default value in case of null:


    var length = name?.length ?: 0  // If name is null, length is 0
    println(length)  // Output: 0
    

A Simple Example Using Null Safety in Kotlin

Now, let’s create an example that demonstrates how to utilize null safety in Android app development with Kotlin. We will create a simple app to input user information.

Project Setup

Open Android Studio and create a new project. Choose the “Empty Activity” template and select Kotlin. Set the project name to “UserInputApp”.

Modifying the Layout File

Open the res/layout/activity_main.xml file in the project and modify it as follows:


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp">

        <EditText
            android:id="@+id/editTextName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Please enter your name" />

        <Button
            android:id="@+id/buttonSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Submit" />

        <TextView
            android:id="@+id/textViewResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp" />

    </LinearLayout>
    

Writing Code for the Main Activity

Now open the MainActivity.kt file and write the following code:


    package com.example.userinputapp

    import android.os.Bundle
    import android.view.View
    import android.widget.Button
    import android.widget.EditText
    import android.widget.TextView
    import androidx.appcompat.app.AppCompatActivity

    class MainActivity : AppCompatActivity() {
        private lateinit var editTextName: EditText
        private lateinit var buttonSubmit: Button
        private lateinit var textViewResult: TextView

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

            editTextName = findViewById(R.id.editTextName)
            buttonSubmit = findViewById(R.id.buttonSubmit)
            textViewResult = findViewById(R.id.textViewResult)

            buttonSubmit.setOnClickListener {
                val name: String? = editTextName.text.toString().takeIf { it.isNotEmpty() }
                textViewResult.text = "Entered name: ${name ?: "No name provided."}"
            }
        }
    }
    

Conclusion

Kotlin’s null safety helps developers minimize unnecessary errors when writing code, enabling them to create safer code. Through the example above, we explored the advantages of null safety and learned how to effectively handle null in Android app development. In the next tutorial, we will look into advanced features of Kotlin and other aspects of Android app development!