Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Generate a Random Number From a Range in Android?

Improve Article
Save Article
  • Last Updated : 30 Jan, 2022
Improve Article
Save Article

In Android, there are multiple libraries that provide mathematical and logical functions to the developers to create meaningful applications. One such function is the random function that generates a random value. However, we can customize this function to not just find a random value but find it from a range of numbers. So in this article, we will show you how you could generate a random value in a range in Android. Follow the below steps once the IDE is ready.

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 two EditText to give two number inputs (range start and end), a TextView to display the result, and a Button to execute the process.


<?xml version="1.0" encoding="utf-8"?>

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.


package org.geeksforgeeks.generaterandomnumber
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import java.util.*
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declaring and Initializing the EditText, 
        // Button and TextView from the layout file
        val mEditText1 = findViewById<EditText>(
        val mEditText2 = findViewById<EditText>(
        val mButton = findViewById<Button>(
        val mTextView = findViewById<TextView>(
        // On button click, min and max value is fetched 
        // from the EditText and a Random value is generated
        mButton.setOnClickListener {
            val minVal = mEditText1.text.toString().toInt()
            val maxVal = mEditText2.text.toString().toInt()
            // For Kotlin>=1.3
            // Inclusive of min and max value
            val mResult = (minVal..maxVal).random() 
            // For Kotlin<1.3
            // mResult = Random().nextInt(maxVal + 1 - minVal) + minVal
            // Random value is displayed in the TextView
            mTextView.text = mResult.toString()


You can see that when the button is clicked, a random number is generated and displayed in the TextView.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!