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 Amit tiwari on How to add a Xamarin Forms Loading Screen/Overlay
3 Oct 2019, 10:29 AM
By Mahmoud Radwan on Xamarin Forms multiple instances of same app open
16 Sep 2019, 21:16 PM
By للل on JQuery Unobtrusive Validation for dynamically created elements
31 Aug 2019, 10:12 AM
By tiky on JQuery Unobtrusive Validation for dynamically created elements
16 Aug 2019, 13:10 PM
By Gerry on Replacing the Xamarin Header/Navigation bar with a custom view/template
11 Jul 2019, 17:12 PM
By steve choi on Xamarin Forms multiple instances of same app open
30 Jun 2019, 09:09 AM
By esrgr on JQuery Unobtrusive Validation for dynamically created elements
11 Jun 2019, 06:01 AM
By annualmars on Raspberry Pi - Running Java app on Raspbian
10 May 2019, 15:48 PM
Categories
App Development
Event
Game Development
Mapping
Modelling
Programming
Review
Robotics
Tutorial
Web Development