javaandroidmultithreadingandroid-runonuithread

Android runOnUiThread() thread is fluctuating


In Android app, I am using NFC reader. There is a listener for that NFC reader in the app. When an NFC tag is read, it triggers the listener in the app. That listener is not in the main thread, but a worker thread.

When that event is called, I need to update the UI with the value. Since It's a worker thread, my code is like:

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                binding.nfc.setVisibility(View.VISIBLE);
                binding.nfcProgressBar.setVisibility(View.VISIBLE);
            }
        });

Where binding is Data Binding the UI components into the View Models.

The problem is with Updating of UI components, even though those line of code inside run() is executed all times. Sometimes it gets updated and sometimes it doesn't.

The NFC will be read continuously in the same activity, the first time I read NFC after opening the app, it works, after that, it fluctuates.

Every time it goes through the runOnUiThread Runnable method but the UI only gets updated sometimes.

I am wondering if There is a problem with my code or runOnUiThread is like that only.

It's fluctuating.


Solution

  • Your question has nothing to do with databinding, it is just using the databinding framework wrapper to hold your findViewById and you are still doing everything else manually. For you it is a glorified ViewHolder pattern.

    If you are using databinding and observables correctly then you should not have to care about your thread. Android will handle that for you. When you update an observable value it will automatically ensure that the correct ui thread is used for updating the ui.

    However, you are not doing this. You are manually using the binding.uielement.property = newValue which is no different then findViewById(someView).property = newValue other then the fact that it already did the findview for you.

    This is not how binding was meant to be used. You may as well go back to standard coding of findById and then set it as you haven't benefited from binding at all.

    If you would like this to be managed by binding. You should create an observable class that you pass in the onCreate to allow it to manage the bindings and the updates for you through properties that update the UI.

    Now if you drop the part relating to binding and just ask what your runOnUIThread problem is, well that's different. Would have to see the full classes involved, the xml of the layout and nested layout you are trying to affect and then we could start to dig in more.