Question

I have an Activity with a TextView, and I set the label and color of the TextView each time a background thread invokes a method on the Activity. It works properly until I leave the Activity and re-enter it. In that case, the TextView is not updated because the Runnable that is posted for execution on the UI thread is not invoked. Perhaps I need to implement something in onResume(), but I don't know what that would be.

Here is how the TextView is assigned when the Activity is created:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_nameserver);
        statusView = (TextView) findViewById(R.id.statusNameserverButton);
        ...
}

And here's the method called by the background thread, which updates the TextView:

public void running(boolean running) {
        final int color;
        final String text;
        if (running) {
            color = Color.GREEN;
            text = "Running";
        } else {
            color = Color.RED;
            text = "Stopped";
        }
        statusView.post(new Runnable() {

            @Override
            public void run() {
                statusView.setTextColor(color);
                statusView.setText(text);
            }

        });
}

In the debugger I see that when running() is invoked after I've re-entered the Activity, the Runnable passed to statusView.post() is never invoked. Inspection of the statusView object properties in the debugger shows no difference between the success and failure cases. I don't know what's different after resuming the Activity that would cause the Runnable to not be invoked. I tried re-assigning the TextView object in onResume(), with the same code used to assign it in onCreate(), but that didn't help.

Was it helpful?

Solution

First check to see if the Activity after resume is the same one as the original Activity, as the original Activity may have been destroyed by Android. Also, check to see if statusView.post(...) returns true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top