Android, updating the UI from another thread

So you can create a background thread for an Android app and happily do your thing. But now you want to update the UI from that thread you've just created and something's causing your app to crash. Your problems most likely solvable by using this simple solution... (This post assumes you know how to make threads, if not then read my last post)

A method called runOnUiThread can be used for the section of code that updates your UI and can be called from wherever you like. Check the solution below:

// This is the thread that works in the background
backgroundUpdate = new Thread(new Runnable()
{
    public void run()
    {
        // Do your thing here...

        // Do this because only the UI thread can update the UI elements.
        runOnUiThread(new Runnable()
        {
            public void run()
            {
                // Put your UI update code here
                TextView titleText = (TextView) findViewById(R.id.title_text);
                titleText.setText(page.getTitle());

                TextView summaryText = (TextView) findViewById(R.id.summary_text);
                summaryText.setText(page.getSummary());
             }
        });
    }
});

Published at

Tags: Android

Luke Alderton

Comments

Share with
Tags
Latest Comments
By Mark Gentry on Windows Server 2019 - Change product key does nothing
20 Aug 2021, 03:30 AM
By Cathy on In-Place Upgrade for a Windows Server domain controller
31 Jul 2021, 18:28 PM
By Mr. Greymatter on Raspberry Pi - Running Java app on Raspbian
16 Feb 2021, 07:35 AM
By Mikko Seittenranta on Xamarin Forms multiple instances of same app open
16 Feb 2021, 04:34 AM
By Andrew on Auto/Custom height on Xamarin Forms WebView for Android and iOS
22 Jan 2021, 22:15 PM
By Nick on Raspberry Pi - Running Java app on Raspbian
14 Oct 2020, 19:37 PM
By Ivan on Fixed: Value cannot be null Parameter Name: source
15 Sep 2020, 19:47 PM
By Anand on Raspberry Pi - Bluetooth using Bluecove on Raspbian
7 Sep 2020, 16:53 PM
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development