Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
Running User Interface Thread in Android using Kotlin
Next article icon

Running User Interface Thread in Android using Kotlin

Last Updated : 23 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, that to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread. 

Realizing UI Thread: 

For example, a thread action is started, and the developer wants to update the front-end element with respect to the thread elements, the runOnUIThread{...} function can be used.

Below is an example of an application where a UI thread is used. 

Sample App in which the Text in the TextView is changed Every Second 

Initially, the application will show a Welcome message and as soon as the start button is clicked, it will show 2 messages, "love gfg" and "not gfg" alternatively at each second. 

Approach: 

Step 1: Add the below code in activity_main.xml. Here, add a TextView and a button to our MainActivity layout.

activity_main.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">      <TextView         android:id="@+id/tv1"         android:layout_width="210sp"         android:layout_height="100sp"         android:layout_centerInParent="true"         android:gravity="center"         android:textSize="50sp"         android:text="Welcome"         />      <Button         android:id="@+id/btnStart"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="Start"         android:layout_below="@id/tv1"         android:layout_centerHorizontal="true"         />  </RelativeLayout> 


Step 2: Add the below code in MainActivity. Here OnClickListener is added with the button. So it is invoked whenever the user clicks the button. In the listener, an infinite loop is created in the main thread and using the UI thread the text is changed after every second. 

MainActivity.kt
class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?)     {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // Assigning Layout elements         val tv = findViewById<TextView>(R.id.tv1)          val btn = findViewById<Button>(R.id.btnStart)          val msg1 = "love gfg" val msg2 = "not gfg"          // Button onClick action         btn.setOnClickListener         {             // Declaring Main Thread             Thread(Runnable {                 while (true) {                     // Updating Text View at current                     // iteration                     runOnUiThread{ tv.text = msg1 }                      // Thread sleep for 1 sec                     Thread.sleep(1000)                     // Updating Text View at current                     // iteration                     runOnUiThread{ tv.text = msg2 }                      // Thread sleep for 1 sec                     Thread.sleep(1000)                 }             }).start()         }     } } 

Note: The While loop must be declared only inside the Thread. If a Thread is declared inside a while loop, the program doesn't work and crashes.

Sample Timer App 

From the basic concept of the above code, a timer app can be designed. Below is the code for the same: 

Approach: 

Step 1: Add the below code in MainActivity layout. Here a button, edittext, and textview are added. The button is used to start the timer, edittext is used to take the input from the user, and textview is used to display the time left. 

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">      <Button         android:id="@+id/btnStart"         android:layout_width="100sp"         android:layout_height="50sp"         android:layout_centerInParent="true"         android:text="Start"         />      <EditText         android:id="@+id/et1"         android:layout_width="100sp"         android:layout_height="100sp"         android:layout_centerHorizontal="true"         android:layout_above="@id/btnStart"         android:textSize="50sp"         android:inputType="number"         android:gravity="center"         android:background="@color/colorPrimary"         android:textColor="@color/colorAccent"         />      <TextView         android:id="@+id/tv1"         android:layout_width="100sp"         android:layout_height="100sp"         android:layout_centerHorizontal="true"         android:layout_below="@id/btnStart"         android:gravity="center"         android:textSize="50sp"         android:background="@color/colorPrimaryDark"         android:textColor="@color/colorAccent"         />  </RelativeLayout> 


Step 2: Add the below code in MainActivity class. Here we add the onClickListener with the button. As the button is clicked, runOnUiThread function is used to display the time left.

MainActivity.kt
class MainActivity : AppCompatActivity() {     override fun onCreate(savedInstanceState: Bundle?)     {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // Assigning Layout elements         val et = findViewById<EditText>(R.id.et1)          val btn = findViewById<Button>(R.id.btnStart)          val tv = findViewById<TextView>(R.id.tv1)                // Button onClick action         btn.setOnClickListener{             // Converting Edit Text input to String             val stringTime= (et.text).toString()             // Converting stringTime to Integer             val intTime= Integer.parseInt(stringTime)             // Declaring Main Thread              Thread(Runnable {                   // For loop Decrement                   for (i in intTime downTo 0) {                        // Updating Text View at                        // current iteration                         runOnUiThread{                             tv.text = i.toString()                          }                     // Thread sleep for 1 sec                         Thread.sleep(1000)                           }                       }).start()         }     } } 

Output:


Next Article
Running User Interface Thread in Android using Kotlin

A

aashaypawar
Improve
Article Tags :
  • Operating Systems
  • Java Quiz
  • Kotlin
  • Android
  • DSA
  • Processes & Threads
  • Kotlin Android

Similar Reads

    How to Send SMS in Android using Kotlin?
    SMS Manager is a class in Android which is used to send the SMS to a specific contact from the android application. We can send text messages, data messages, and multimedia messages using this class. There are different methods that are provided to send different types of messages. In this article,
    4 min read
    Implement Universal Image Loader Library in Android using Kotlin
    Universal Image Loader library is also referred to as (UIL). It is similar to Picasso and Glide which is used to load the images from the URL within our image view inside our android application. This image loading library has been created to provide a powerful, flexible, and customizable solution t
    4 min read
    MultiThreading in Android with Examples
    Working on multiple tasks at the same time is Multitasking. In the same way, multiple threads running at the same time in a machine is called Multi-Threading. Technically, a thread is a unit of a process. Multiple such threads combine to form a process. This means when a process is broken, the equiv
    3 min read
    Design Patterns in Android with Kotlin
    Design patterns is basically a solution or blueprint for a problem that we get over and over again in programming, so they are just typical types of problems we can encounter as programmers, and these design patterns are just a good way to solve those problems, there is a lot of design pattern in an
    5 min read
    JSON Parsing in Android Using Volley Library with Kotlin
    JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences