View.setVisibility ignored when loading data [closed]

View.setVisibility does not work in specific cases. Here is an example:

Works fine:

void A()
{
    View1.setVisibility(View.VISIBLE);
    View2.setVisibility(View.GONE);
}

SetVisibility ignored, rest executed:

void B()
{
    View1.setVisibility(View.VISIBLE);
    View2.setVisibility(View.GONE);

    for (String path: dataPaths)
    {
        // Loading data
    }
}

I tried:

Answer

Your code is performing potentially expensive I/O and image processing tasks on the UI thread, this is why your Visibility calls appear to not work…you’re effectively hanging all UI updates while this expensive work is being performed.

Threading and background processing is complex. AsyncTask was once a popular means of doing simple background tasks but it’s been marked deprecated as of API 30.

Suggested reading:

https://developer.android.com/guide/background

You’ll want to learn how to dispatch work to a background thread, then how the background thread can dispatch UI updates back to the main thread when complete.

Additionally you might consider using WorkManager as a way of scheduling and managing background tasks:

https://developer.android.com/topic/libraries/architecture/workmanager

The Guide to background processing offers suggestions on this also.