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

Post a comment
Sit tight...
We're adding your comment.
Thank you.
Your comment has been added.
There's been a problem.
Please try again later.
Share with
Tags
Latest Comments
By Ben on Raspberry Pi - Running Java app on Raspbian
24 May 2020, 09:01 AM
By BP on Disabling XAML Hot Reload
14 May 2020, 21:59 PM
By Andy on Xamarin Forms - Working with threads
12 May 2020, 09:16 AM
By mitchell on Xamarin forms - Stop/Cancel back button event
29 Apr 2020, 18:16 PM
By Paolo on Raspberry Pi - Running Java app on Raspbian
19 Apr 2020, 11:04 AM
By Alexander Gontar on Xamarin Forms - Working with threads
13 Mar 2020, 07:10 AM
By Arthur Richardson on Disabling XAML Hot Reload
12 Mar 2020, 17:52 PM
By George on Xamarin Forms - Working with threads
10 Mar 2020, 05:04 AM
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development