What is the Android UiThread?


The Android UIThread is the main thread of the Android operating system. It is responsible for handling all user interface components and events.

The UIThread is responsible for creating and managing the user interface, from creating the Activity and Fragment objects to handling user input, and drawing the user interface on the screen. The UIThread is responsible for executing the main loop of the application, which is responsible for updating the user interface and responding to user input. This loop is constantly running, even when the user is not interacting with the application. This ensures that the application always remains responsive and up-to-date.

In this article we will be building a simple application which will display a multiplication table for a specific number and the table will be generated on Android UI Thread.

Implementation

We will be creating a simple application in which we will be taking the input from the user in the form of a number. Then we will be generating the table from 1 to 10 for that number on Android’s UI Thread and display that table inside our application. We will be following a step by step guide to implement a toast message in an android application.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Kotlin.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?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:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- creating an edit text for entering the number to generate table -->
   <EditText
      android:id="@+id/idEdtNumber"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginStart="20dp"
      android:layout_marginTop="20dp"
      android:layout_marginEnd="20dp"
      android:layout_marginBottom="20dp"
      android:hint="Number"
      android:inputType="phone" />

   <!-- button to generate the table-->
   <Button
      android:id="@+id/idBtnGenerate"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idEdtNumber"
      android:layout_margin="10dp"
      android:text="Generate Table"
      android:textAllCaps="false" />

   <!-- text view for displaying  heading of the table -->
   <TextView
      android:id="@+id/idTVTableOf"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idBtnGenerate"
      android:text="Table of : "
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="@color/black"
      android:textSize="18sp"
      android:textStyle="bold" />

   <!-- text view for displaying the table of a number -->
   <TextView
      android:id="@+id/idTVTable"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_below="@id/idTVTableOf"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Table"
      android:textAlignment="center"
      android:textAllCaps="false"
      android:textColor="@color/black"
      android:textSize="18sp" />
</RelativeLayout>

Explanation − In the above code the root element is a Relative layout in android. This layout is a view group which is used to align all the elements within it relative to each other. We can relatively align all elements within Relative Layout with the help of ids or positions.

Inside this relative layout we are firstly creating an edit text inside which the user will enter the number for which he has to generate the table. After that we are creating a button to generate the table. Then we are displaying a text view to display the heading of the table. After that we are creating one more text view in which we will be displaying the table for the number which is being entered by the user.

At last we are adding a closing tag for our Relative Layout as the text view and button is enclosed in our relative layout.

Step 3 : Working with MainActivity.java

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

   // on below line we are creating variables.
   private EditText numberEdt;
   private TextView tableOfTV;
   private TextView tableTV;
   private Button generateTableBtn;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line we are initializing all our variables.
      numberEdt = findViewById(R.id.idEdtNumber);
      tableOfTV = findViewById(R.id.idTVTableOf);
      tableTV = findViewById(R.id.idTVTable);
      generateTableBtn = findViewById(R.id.idBtnGenerate);

      // on below line we are adding click listeners for our button.
      generateTableBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line we are setting heading for our table tv.
            tableTV.setText("");
            tableOfTV.setText("Table of : " + numberEdt.getText().toString());
            // on below line getting number.
            String num = numberEdt.getText().toString();
            // on below line parsing number.
            int number = Integer.parseInt(num);
            // on below line we are creating a thread.
            Thread thread = new Thread() {
               @Override
               public void run() {
               super.run();
                  // on below line running a for loop to display our table.
                  for (int i = 1; i < 11; i++) {
                     // on below line we are make calculations for our table.
                     int a = number * i;
                     String ct = tableTV.getText().toString();
                     String txt = numberEdt.getText().toString() + " * " + " " + i + " = " + a;
                     runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                           // on below line appending the text to our text view.
                           tableTV.append("
" + txt); } }); // on below line we are sleeping the thread for 1 second. try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }; // on below line we are starting the thread. thread.start(); } }); } }

Explanation − In the above code for MainActivity.java file. Firstly we are creating a variable for the different views which we have created such as button, text views and an edit text.

Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file.

After specifying the view, we are initializing all the variables for our text views, buttons and and our edit text. After that we added a click listener for our button to generate the table.

Inside the onclick method we are getting the number from the edit text field, then we are creating a thread and running a thread. Inside this thread we are running a loop to display the table of a specific number inside our text view. Then we are making our thread to sleep for 1 second and lastly calling start method to start our thread.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have taken a look at What is Android UiThread and How we can use this Ui Thread within our application to display the table of a specific number inside our application.

Updated on: 30-Mar-2023

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements