How to Get Current Default Language of Android Device Programmatically?

Smartphones seem to be predicting and showing us results from what we think in our minds. If you think of traveling, you shall soon expect something related to it in your device’s feed. This is the next level of technology, where data helps in developing businesses. The software collects personal data like recent searches, device location, etc., to generate the feed. An important factor contributing to personal data is the device’s default language, and it helps better understand the device’s location. So, business in multiple ways provides various services and information available in that location to the user.

In this article, we shall focus on fetching the default language of the device.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Button in the layout file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
 
  <!--This button on click will
      generate a Toast message
       displaying default language-->
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="click"/>
 
</RelativeLayout>


 
Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. 

Kotlin




import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import java.util.*
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // Declaring button from the layout
        val mButton = findViewById<Button>(R.id.btn)
         
        // When button is clicked, a Toast message is
        // displayed showing the current default language
        mButton.setOnClickListener {
            Toast.makeText(applicationContext, Locale.getDefault().language.toString(), Toast.LENGTH_SHORT).show()
        }
    }
}


Output: