Switch case in Android Studio can be used to create multiple possible outcomes for a given variable.

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

This variable can be a Primitive data type i.e, Integer, bit, short or char or even a String Class. But it can not be a boolean.

switch case in android
switch case flowchart

In the example below we will show you code for both Java and Kotlin Programming languages where we will be using the switch case statement in the Android Studio.

When to use Switch case in Android

Switch cases have certain limitations and before starting up with example we would like to discuss a few cases in which we can not use a switch statement.

  1. Boolean Input: Switch statements can not accept Boolean statements as input. It can only be a Primitive data type i.e, Integer, bit, short or char or even a String Class.
  2. Boolean Values: Unlike if-else statement where you calculate outcome on the basis of a possibility. Switch statements can be used for fixed data values. The cases inside the switch statement are fixed values and can’t be a boolean.
  3. Testing Expression: Switch statement can not be used to test expression. i.e, you can not have cases where case 20 > 5.

Example Code

In the following example, we will be using the switch statement to set the text of a textview widget basis of the int between 1 to 7 of the week.

To get started, create an xml file activity_main.xml with following line of code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:inputType="number"
        android:hint="Type a number from 1 to 7"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:text="Get Day of the week"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

</androidx.constraintlayout.widget.ConstraintLayout>

Switch case in Java

To do a switch case in Java, here is the code:

package com.aaveti.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText editText = findViewById(R.id.editText);
        Button button = findViewById(R.id.btn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String num;

                if(editText.getText() != null) {
                    num = editText.getText().toString();

                    switch (num){
                        case "1":
                            showToast("MONDAY");
                            break;
                        case "2":
                            showToast("TUESDAY");
                            break;
                        case "3":
                            showToast("WEDNESDAY");
                            break;
                        case "4":
                            showToast("THURSDAY");
                            break;
                        case "5":
                            showToast("FRIDAY");
                            break;
                        case "6":
                            showToast("SATURDAY");
                            break;
                        case "7":
                            showToast("SUNDAY");
                            break;
                        default:
                            showToast("---INVALID---");
                            break;
                    }
                }

            }
        });

    }

    void showToast(String msg){
        Toast.makeText(MainActivity.this,"The day of the week is " + msg,Toast.LENGTH_LONG).show();
    }
}

Switch or When case in Kotlin

To do a switch case in Kotlin, here is the code:

package com.aaveti.myapplication

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

class Main2Activity : AppCompatActivity() {

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

        val editText : EditText? = findViewById(R.id.editText)
        val button : Button? = findViewById(R.id.btn)

        button?.setOnClickListener {
            val num: String

            if (editText != null) {
                if (editText.text != null) {
                    num = editText.text.toString()

                    when (num) {
                        "1" -> showToast("MONDAY")
                        "2" -> showToast("TUESDAY")
                        "3" -> showToast("WEDNESDAY")
                        "4" -> showToast("THURSDAY")
                        "5" -> showToast("FRIDAY")
                        "6" -> showToast("SATURDAY")
                        "7" -> showToast("SUNDAY")
                        else -> showToast("---INVALID---")
                    }
                }
            }
        }

    }

    private fun showToast(msg: String) {
        Toast.makeText(this@Main2Activity, "The day of the week is $msg", Toast.LENGTH_LONG).show()
    }
}

The switch case is known as when in Kotlin. As you can see in the example above it is when(variable){ all possible cases }

TaDa, so here we are done with switch case example in Android. Do let me know in the comment section below if you faced any issues or need any further explaination.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like